import tkinter as tk
from tkinter import IntVar
from tkinter import filedialog

window = tk.Tk()
window.title("Queclink Tool")
# 禁止用户调整窗口的大小，第一个参数为宽度方向，第二个参数为高度方向
window.resizable(False, False)
# 窗口居中操作
width = 500
height = 200
# 获取当前屏幕的宽度和高度窗口居中
screenwidth = window.winfo_screenwidth()
screenheight = window.winfo_screenheight()
size_geo = '%dx%d+%d+%d' % (width, height, (screenwidth - width) // 2, (screenheight - height) // 2)
window.geometry(size_geo)


global lengthvar
global device_typevar
global protocol_version
global firmware_version
global firmware_version
global device_type_lengthvar


def get_hex_value(s):
    # 提取字符串末尾的十六进制部分
    s = s.strip()
    # 检查字符串是否为空或者是否以特定错误提示开头
    if not s or s.startswith("Warning:") or s.startswith("GET"):
        return None
    try:
        # 分割字符串并取最后一部分，同时移除首尾的 $ 和换行符
        hex_part = s.split(',')[-1].strip('$\n')
        # 将十六进制字符串转换为整数
        return int(hex_part, 16)
    except (ValueError, IndexError):
        # 如果转换失败或者分割后没有元素，返回 None
        return None

def get_hex(s):
    # 提取字符串末尾的十六进制部分
    s = s.strip()
    # 检查字符串是否为空或者是否以特定错误提示开头
    if not s or s.startswith("Warning:") or s.startswith("GET"):
        return None
    try:
        # 分割字符串并取最后一部分，同时移除首尾的 $ 和换行符
        hex_part = s[-12:-4].strip('$\n')
        # 将十六进制字符串转换为整数
        return int(hex_part, 16)
    except (ValueError, IndexError):
        # 如果转换失败或者分割后没有元素，返回 None
        return None
    
def convert_hex_to_decimal(hex_str):
    """将16位十六进制字符串转换为带符号的十进制数"""
    value = int(hex_str, 16)
    # 检查最高位是否为1（对于16位数，最高位为1的阈值是0x8000）
    if value & 0x8000:  # 如果最高位为1，表示负数
        # 计算补码对应的正值并取负
        return -((~value & 0xFFFF) + 1)
    else:  # 最高位为0，表示正数
        return value


def crd_analyze():
    filepath = filedialog.askopenfilename(filetypes = [('TXT', '*.txt')])
    crd_lines = []

    with open(filepath, "r", encoding='utf-8') as file:
        lines = file.readlines()

    for line in lines:
        if line.find('+RESP:GTCRD') != -1 or line.find('+BUFF:GTCRD') != -1:
            ascii_hex = 0
        else:
            ascii_hex = 1
    xyz_value = []
    print('ascii_hex',ascii_hex)
    if ascii_hex == 0:
        for line in lines:
            new_line = None
            if '+RESP:GTCRD' in line:
                index = line.index('+RESP:GTCRD')
                new_line = line[index:].lstrip()
            elif '+BUFF:GTCRD' in line:
                index = line.index('+BUFF:GTCRD')
                new_line = line[index:].lstrip()
            if new_line:
                crd_lines.append(new_line)
        sort_crd_lines = sorted(crd_lines, key=get_hex_value)

        for crd_line in sort_crd_lines:
            parts = crd_line.split(',')
            crd_value = parts[8]
            groups = [crd_value[i:i + 12] for i in range(0, len(crd_value), 12)]
            for group in groups:
                x = group[0:4]
                y = group[4:8]
                z= group[8:12]
                x_value = convert_hex_to_decimal(x)
                y_value = convert_hex_to_decimal(y)
                z_value = convert_hex_to_decimal(z)
                xyz_value.append(f"{x_value},{y_value},{z_value}\n")
        with open('crd.txt', 'w', encoding='utf-8') as file:
            # 将结果列表中的所有行写入文件
            file.writelines(xyz_value)

    if ascii_hex == 1:
        for line in lines:
            new_line = None
            if '2B435244' in line:
                index = line.index('2B435244')
                new_line = line[index:].lstrip()
            if new_line:
                crd_lines.append(new_line)
        sort_crd_lines = sorted(crd_lines, key=get_hex)


        for crd_line in sort_crd_lines:
            bit_0 = 1 if lengthvar.get() else 0
            bit_1 = 1 if device_typevar.get() else 0
            bit_2 = 1 if protocol_version.get() else 0
            bit_3 = 1 if firmware_version.get() else 0
            mask = bit_3 * 8 + bit_2 * 4 + bit_1 * 2 + bit_0

            if device_type_lengthvar.get() == 1:
                bit_data = {
                    0: 4,  # bit0 控制 4 个数据
                    1: 6,  # bit1 控制 2 个数据
                    2: 4,  # bit2 控制 4 个数据
                    3: 4  # bit3 控制 4 个数据
                }
            else:
                bit_data = {
                    0: 4,  # bit0 控制 4 个数据
                    1: 2,  # bit1 控制 2 个数据
                    2: 4,  # bit2 控制 4 个数据
                    3: 4  # bit3 控制 4 个数据
                }

            total = 0
            # 遍历每个bit位置
            for bit_position, data_count in bit_data.items():
                # 检查对应的bit是否被设置
                if mask & (1 << bit_position):
                    total += data_count

            index = total + 36
            data_length  = crd_line[index: index+4]
            print(data_length)
            data_length_int = int(data_length, 16)
            crd_value = crd_line[index+4: index+data_length_int * 2+4]
            groups = [crd_value[i:i + 12] for i in range(0, len(crd_value), 12)]
            for group in groups:
                x = group[0:4]
                y = group[4:8]
                z = group[8:12]
                #print(x,y,z)
                x_value = convert_hex_to_decimal(x)
                y_value = convert_hex_to_decimal(y)
                z_value = convert_hex_to_decimal(z)
                xyz_value.append(f"{x_value},{y_value},{z_value}\n")
        with open('crd.txt', 'w', encoding='utf-8') as file:
            # 将结果列表中的所有行写入文件
            file.writelines(xyz_value)

lengthvar = IntVar()
device_typevar = IntVar()
protocol_version = IntVar()
firmware_version = IntVar()
device_type_lengthvar = IntVar()

lengthvar.set(1)
device_typevar.set(1)
protocol_version.set(1)
firmware_version.set(1)
device_type_lengthvar.set(1)

length = tk.Checkbutton(window, text="Length", variable=lengthvar, onvalue=1, offvalue=0)
length.place(relx=0.01, rely=0.05)
device_type = tk.Checkbutton(window, text="Device Type", variable=device_typevar, onvalue=1, offvalue=0)
device_type.place(relx=0.30, rely=0.05)
device_type_length = tk.Checkbutton(window, text="Device Type长度为3", variable=device_type_lengthvar, onvalue=1, offvalue=0)
device_type_length.place(relx=0.60, rely=0.05)
protocol = tk.Checkbutton(window, text="Protocol Version", variable=protocol_version, onvalue=1, offvalue=0)
protocol.place(relx=0.01, rely=0.5)
firmware = tk.Checkbutton(window, text="Firmware Version", variable=firmware_version, onvalue=1, offvalue=0)
firmware.place(relx=0.30, rely=0.5)
crd_but = tk.Button(window, text='CRD解析', pady=1, padx=1, command=crd_analyze, width=10)
crd_but.place(relx=0.8, rely=0.5)

window.mainloop()
